package com.zframeworks.core;

import com.zframeworks.ImService;
import com.zframeworks.core.bean.Message;
import com.zframeworks.core.bean.Result;
import com.zframeworks.core.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

@Component
public class WebSocketHandler extends AbstractWebSocketHandler {

    @Autowired
    private ImService imService;


    /**
     * 建立链接
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userid = String.valueOf(session.getAttributes().get("userid"));

        if(z.isNotNull(userid)){
            //保存用户信息
            User u = new User();
            u.setUserid(userid);
            String name = String.valueOf(session.getAttributes().get("name"));
            if(z.isNotNull(name)){
                u.setName(name);
            }
            u.setWebSocketSession(session);
            z.users.put(userid,u);
            z.sessions.put(session.getId(),userid);

            z.Log("用户登录|"+userid);
        }else{
            //通知用户登录失败
            imService.SendSystemMessage(session,"登录失败|userid不可为空");

            //关闭用户连接
            session.close();
        }
    }



    /**
     * 接到信息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        Result mr = imService.vMessage(message);
        if(mr.ifSuccess()){
            //获取消息体对象
            Message m = (Message)mr.getData();
            if(z.isNotNull(m)){
                //获取用户信息
                User user = z.users.get(m.getTo());
                if(z.isNotNull(user) && z.isNotNull(user.getWebSocketSession()) && user.getWebSocketSession().isOpen()){
                    z.Log("消息ID："+m.getZid()+"|发送人："+m.getFrom()+"|接收人："+m.getTo()+"|消息类型："+m.getType()+"|时间："+m.getTime()+"|消息体："+m.getMsg());
                    imService.SendMessage(user.getWebSocketSession(),m);
                    imService.SendSystemMessage(session,"您的消息已发送");
                }else{
                    imService.SendSystemMessage(session,m.getTo()+"未在线");
                }
            }else{
                imService.SendSystemMessage(session,"message is null");
            }
        }else{
            imService.SendSystemMessage(session,mr.getMsg());
        }
    }

    /**
     * 断开连接
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userid = z.sessions.get(session.getId());
        if(z.isNotNull(userid)){
            z.users.remove(userid);
            z.sessions.remove(session.getId());
            z.Log(userid+"|已下线");
        }
        super.afterConnectionClosed(session, status);
    }


    /**
     * 输出当前服务器连接人数
     */
    @Scheduled(cron = "*/5 * * * * ?")//每个5秒执行一次任务(方法)
    private void printSessionCustomer(){
        z.Log("当前在线人数："+z.users.size());
        z.Log("[");
        for (String userid : z.users.keySet()) {
            User u = z.users.get(userid);

            //判读当前session是否连接状态，如果不是，直接删除
            WebSocketSession ws = u.getWebSocketSession();
            if(!ws.isOpen()){
                //已下线
                z.users.remove(userid);
                z.sessions.remove(u.getWebSocketSession().getId());
                z.Log(u.getUserid()+"|已下线");
            }else{
                if(z.isNotNull(u.getName())){
                    z.Log("["+u.getUserid()+":"+u.getName()+"] ");
                }else{
                    z.Log("["+u.getUserid()+"] ");
                }

            }

        }
        z.Log("]");
    }

}
